package pri.zxx.webdemo.interceptor;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import pri.zxx.webdemo.utils.MDCUtil;
import pri.zxx.webdemo.utils.TokenHolder;

import java.io.IOException;

/**
 * 使用resttemplate的时候 透传requestId
 *
 * @author wangn <15124178@qq.com> 2020/8/4
 */
@Component
@ConditionalOnClass(ClientHttpRequestInterceptor.class)
@ConditionalOnProperty(value = "custom.log.trace.enable", matchIfMissing = true)
public class TraceLogRestTemplateInterceptor implements IClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().set(MDCUtil.REQUEST_ID, MDCUtil.initRequestId());
        request.getHeaders().set("token", TokenHolder.get());
        return execution.execute(request, body);
    }
}
